<?php

/**
 * 日志模型类
 */

namespace app\api\model;

use app\api\model\Common;

class Log extends Common
{
    protected $_level = ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug'];
    protected $_type = [
        'create' => '增加',
        'read' => '查看',
        'update' => '更新',
        'delete' => '删除',
        'login' => '登录',
        'logout' => '登出',
        'download' => '下载',
        'upload' => '上传'
    ];
    /**
     * 获取日志操作用户所属的详情
     * @param  array   $param  [description]
     */
    public function users()
    {
        return $this->hasOne('User', 'id', 'uid')->field('id,username');
    }

    /**
     * 获取数据列表
     */
    public function getDataList($map, $limit, $page)
    {
        try {
            $field = [
                'log.id','log.ip as IP','log.create_time','user.username as create_user','log.type','log.rule'
            ];
            $list = $this->alias('log')->join('admin_user user', 'user.id = log.uid', 'LEFT')->where($map)->field($field)->limit($limit)->page($page)->order('log.id desc')->select();
            $count = $this->alias('log')->join('admin_user user', 'user.id = log.uid', 'LEFT')->where($map)->count();
            $rule_model = Model('rule');
            foreach ($list as &$value) {
                $rule = $rule_model->get(['name' => explode('-', strtolower($value['rule']))['1']]);
                $value['module_name'] = $rule->title;
                $value['action_name'] = $rule_model->get(['name' => explode('-', strtolower($value['rule']))['2'], 'pid' => $rule->id])->title;
                $value['type'] = $this->_type[$value['type']];
            }
            $result = [
                'list' => $list,
                'total' => $count,
                'totalPage' => ceil($count / $page)
            ];
            return $result;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 获取文件
     */
    public function getDetail($id)
    {
        try {
            $data = $this->get($id);
            if (!$data) {
                $this->error = '未找到数据';
                return false;
            }
            $return = [
                'username' => $data->users->username,
                'url' => $data->url,
                'comment' => $data->comment,
                'action' => $data->rule,
            ];
            return $return;
        } catch (\Exception $e) {
            echo $e->getMessage();
            $this->error = '抛出异常';
            return false;
        }
    }

    /**
     * 添加日志
     */
    public function add($param)
    {
        try {
            $param['level'] = array_keys($this->_level, $param['level']);
            $param['create_time'] = time();
            $this->data($param)->allowField(true)->save();
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 查询所有日志
     */
    public function getAllData($map){
        try {
            $filename = fopen(config('huisheng.word_result') . 'log.txt', 'w');
            if (flock($filename, LOCK_EX)) {  // 进行排它型锁定
                $this->with('users')->where($map)->chunk(1,function($logs) use ($filename){
                    foreach($logs as $log){
                        $log['type'] = $this->_type[$log['type']];
                        $log['level'] = $this->_level[$log['level']];
                        fwrite($filename, json_encode($log, JSON_UNESCAPED_UNICODE) . "\r\n");
                    }
                });
                flock($filename, LOCK_UN);    // 释放锁定
            } else {
                $this->error = "Couldn't get the lock!";
                return false;
            }
            fclose($filename);
            return config('huisheng.word_result') . 'log.txt';
        } catch (\Exception $e) {
            fclose($filename); 
            $this->error = $e->getMessage();
            return false;
        }
    }


}
